<template>
  <div>
    <el-row :gutter="20" class="containerBox">
      <el-col :span="24" style="text-align: left">
        <el-form :inline="true" :model="search" class="demo-form-inline" size="mini">
          <el-form-item label="所属平台:">
            <el-tooltip class="item" effect="dark"  placement="top">
              <div slot="content" v-html="selectContent"></div>
              <el-select
                clearable
                filterable
                multiple
                collapse-tags
                v-model="search.platformIds"
                @change="selectChange"
                placeholder="请选择平台">
                <el-option
                  v-for="item in platformList"
                  :key="item.platformId"
                  :label="item.platformName"
                  :value="item.platformId">
                </el-option>
              </el-select>
            </el-tooltip>
          </el-form-item>
          <el-form-item label="操作系统:">
            <el-checkbox-group v-model="search.operaSys">
              <el-checkbox
                v-for="(item,index) in systemOpe"
                :key="index"
                :label="item"
              ></el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="日期:">
            <el-date-picker
              class="searchDom"
              value-format="yyyy-MM-dd"
              v-model="search.dateTime"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getData">查询</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <el-row class="">
      <el-col :span="24">
        <el-table
          v-if="isShowTab"
          size="mini"
          :data="tableData"
          row-key="id"
          height="500"
          border
          lazy
          :load="load"
          :expand-row-keys="expendRowKeys"
          @expand-change="getExpendRows"
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
          style="width: 100%">
          <el-table-column
            v-for="(item, index) in tableColumn"
            align="center"
            :key="index"
            :prop="item.prop"
            :label="item.label"
            :fixed="item.fixed"
            :width="item.width"
          >
            <template slot-scope="scope">
              <myRender
                v-if="item.render"
                :row="scope.row"
                :render="item.render">
              </myRender>
              <span v-else>
             {{scope.row[item.prop]}}
           </span>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <!--    <el-row class="containerBox" style="margin-top: 40px">-->
    <!--      <el-col :span="24" style="text-align: right">-->
    <!--        <el-pagination-->
    <!--          @size-change="handleSizeChange"-->
    <!--          @current-change="handleCurrentChange"-->
    <!--          :current-page="search.pageNumber"-->
    <!--          :page-sizes="[10, 200, 300, 400]"-->
    <!--          :page-size="search.pageSize"-->
    <!--          layout="total, sizes, prev, pager, next, jumper"-->
    <!--          :total="400">-->
    <!--        </el-pagination>-->
    <!--      </el-col>-->
    <!--    </el-row>-->
    <tableDialog
      :fullscreenLoading="fullscreenLoading"
      @diaTableClosed="closeDiaTable"
      :isShow="showTableDia"
      :tableColumn="diaTable"
      :diaTitle="diaTitleText"
      :tableData="diaTabData"/>
  </div>
</template>
<script>
  import myRender from '@/components/tableRender';
  import tableDialog from '@/components/tableDialog';
  import {
    getNettrafficData,
    getPlatfromList,
    getNettrafficChild,
    getUvTimesTableData,
    getUvTimesTableDataOfHours,
    getUvDaysTableData,
    getUvDaysTableDataOfHour,
  } from '@/api';

  const dateNow = moment().format('YYYY-MM-DD');
  export default {
    name: 'nettrafficAls',
    data() {
      return {
        isFirstOpenPage: 1,
        fullscreenLoading: false,
        showTableDia: false,
        isShowTab: false,
        diaLoading:false,
        diaTable: [],
        diaTabData: [],
        diaTitleText: '',
        selectContent:'',
        search: {
          dateTime: [dateNow, dateNow],
          platformIds: [],
          operaSys: [],
          pageNumber: 1,
          pageSize: 10,
          lastAppSyS: [],
        },
        expendRowKeys: [],
        systemOpe: ['Android', 'IOS'],
        platformList: [],
        tableData: [],
        tableColumn: [
          {prop: 'timeStr', label: '日期', fixed: 'left', width: '160',},
          {prop: 'platformName', label: '平台', width: '160', fixed: 'left',},
          {prop: 'totalClickNum', label: '文章阅读数',},
          {prop: 'clickAdRatio', label: '广告点击率',},
          {prop: 'secondShareRatio', label: '二次分享率'},
          {prop: 'sessionRatio', label: '好友占比'},
          {prop: 'groupRatio', label: '群占比'},
          {prop: 'timeLineRatio', label: '朋友圈占比'},
          {prop: 'spreadRatio', label: '展开全文占比',},
          {prop: 'addPoint', label: '加分行为',},
          {prop: 'validAddPoint', label: '有效加分',},
          {prop: 'baiduIpCount', label: 'IP数',},
          {prop: 'singleReadPoint', label: '单ip金豆(元)',},
          {prop: 'illegalAddPointRatio', label: '扣量比例',},
          {prop: 'averageRollTime', label: '平均滚动次数',},
          {prop: 'stopTime', label: '停留时长(s)',},
          {prop: 'inexactAdStopTime', label: '伪广告时长(s)',},
          {prop: 'exactAdStopTime', label: '准广告时长(s)',},
          {prop: 'backRatio', label: '返回率',},
          {prop: 'scanRatio', label: '扫码率',},
          {
            prop: '', label: '操作', fixed: 'right', width: '160',
            render: (h, params) => {
              return h('div', [
                h('el-button', {
                  props: {
                    type: 'text',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.showDiaTable(params, 'uvTimes');
                    }
                  }
                }, 'UV次数'),
                h('el-button', {
                  props: {
                    type: 'text',
                    size: 'small'
                  },
                  style: {},
                  on: {
                    click: () => {
                      this.showDiaTable(params, 'uvDays');
                    }
                  }
                }, 'UV天数')
              ]);
            }
          },
        ]
      }
    },
    components: {
      myRender,
      tableDialog
    },
    created() {
      this.getData();
    },
    mounted() {

    },
    methods: {
      getExpendRows(rows, expanded) {
        // console.log(rows);
        // console.log(expanded);

        var index = this.expendRowKeys.indexOf(rows.id);
        if (expanded && (index == -1)) {
          this.expendRowKeys.push(rows.id)
        }
        if (!expanded && (index != -1)) {
          this.expendRowKeys.splice(index, 1);
        }
        // console.log(this.expendRowKeys);
      },
      async getData() {
        var _this = this;
        var lastSelect = localStorage.getItem('nettrafficAls:platformIds');
        _this.isFirstOpenPage++;
        // this.fullscreenLoading = true;
        this.isShowTab = false;
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        this.expendRowKeys = [];
        await this.getPlatformList();
        if (_this.isFirstOpenPage == 2) {
          if (lastSelect != "undefined") {
            // console.log(lastSelect);
            if (lastSelect) {
              lastSelect = lastSelect.split(",");
            } else {
              lastSelect = [];
            }
            this.search.platformIds = lastSelect;
          }
          _this.selectChange();
        }
        var dateRange = this.search.dateTime;
        var operSysArr = this.search.operaSys;
        var params = {
          beginDate: "",
          endDate: "",
          platformIds: this.search.platformIds,
          appSystems: []    // 0: 安卓，1：苹果
        };
        localStorage.setItem('nettrafficAls:platformIds', _this.search.platformIds);
        if (dateRange) {
          params.beginDate = dateRange[0];
          params.endDate = dateRange[1];
        }
        if (operSysArr.indexOf('Android') != -1) {
          params.appSystems.push(0);
        }
        if (operSysArr.indexOf('IOS') != -1) {
          params.appSystems.push(1);
        }
        this.search.lastAppSyS = params.appSystems;
        getNettrafficData(params).then(({data}) => {
          this.tableData = data.result;
          this.isShowTab = true;
          // this.fullscreenLoading = false;
          this.$nextTick(() => { // 以服务的方式调用的 Loading 需要异步关闭
            loading.close();
          });
        });
      },
      selectChange(){
        var selectContent = '';
        const selectList = this.platformList;
        const data = this.search.platformIds;
        selectList.map((item,index) => {
            if(data.indexOf(item.platformId) != -1){
              selectContent = selectContent + `${item.platformName}<br />`
            }
        });
        // console.log(selectContent);
        this.selectContent = selectContent || "暂无数据";
      },
      getPlatformList() {
        return getPlatfromList().then(({data}) => {
          this.platformList = data.platformList;
        });
      },
      async load(tree, treeNode, resolve) {
        // console.log(tree);
        // console.log(treeNode);
        var params = {
          dateStr: tree.timeStr,
          platformId: tree.platformId,
          appSystems: this.search.lastAppSyS
        };
        const data = await getNettrafficChild(params).then(({data}) => {
          return data.result;
        });
        // console.log(data);
        // console.log(1);
        resolve(data);
      },
      closeDiaTable() {
        this.showTableDia = false;
        this.fullscreenLoading = false;
        this.diaTable = [];
        this.diaTabData = [];
        this.diaTitleText = '';
      },
      async showDiaTable(record, type) {
         this.diaTable = [
          {prop: 'id', label: type == 'uvTimes'?'cookie次数':'cookie天数', fixed: 'left', width: 110,},
          // {prop: 'addPoint', label: '加分行为',},
          // {prop: 'averageRollTime', label: '平均滚动',},
          // {prop: 'backRatio', label: '返回率',},
          // {prop: 'clickAdRatio', label: '广告点击率',},
          // {prop: 'exactAdStopTime', label: '准广告时长',},
          // {prop: 'groupRatio', label: '群占比',},
          // {prop: 'illegalAddPointRatio', label: '扣量比例',},
          // {prop: 'inexactAdStopTime', label: '伪广告时长',},
          // {prop: 'scanRatio', label: '扫码率',},
          // {prop: 'secondShareRatio', label: '二次分享率',},
          // {prop: 'sessionRatio', label: '好友占比',},
          // {prop: 'singleReadPoint', label: '单ip金豆',},
          // {prop: 'spreadRatio', label: '展开全文占比',},
          // {prop: 'stopTime', label: '停留时长',},
          // {prop: 'timeLineRatio', label: '朋友圈占比',},
          // {prop: 'totalClickNum', label: '文章阅读数',},
          // {prop: 'validAddPoint', label: '有效加分',},
          {prop: 'totalClickNum', label: '文章阅读数',},
          {prop: 'clickAdRatio', label: '广告点击率',},
          {prop: 'secondShareRatio', label: '二次分享率'},
          {prop: 'sessionRatio', label: '好友占比'},
          {prop: 'groupRatio', label: '群占比'},
          {prop: 'timeLineRatio', label: '朋友圈占比'},
          {prop: 'spreadRatio', label: '展开全文占比',},
          {prop: 'addPoint', label: '加分行为',},
          {prop: 'validAddPoint', label: '有效加分',},
          {prop: 'singleReadPoint', label: '单阅读金豆(元)',},
          {prop: 'illegalAddPointRatio', label: '扣量比例',},
          {prop: 'averageRollTime', label: '平均滚动次数',},
          {prop: 'stopTime', label: '停留时长(s)',},
          {prop: 'inexactAdStopTime', label: '伪广告时长(s)',},
          {prop: 'exactAdStopTime', label: '准广告时长(s)',},
          {prop: 'backRatio', label: '返回率',},
          {prop: 'scanRatio', label: '扫码率',},
        ];
        this.showTableDia = true;
        this.fullscreenLoading = true;
        var params = {
          platformId: record.platformId,
          staticsDate: record.timeStr,
          appSystems: this.search.lastAppSyS
        };
        var diaTitle = `${record.platformName} ${record.timeStr} 日 `;
        const isDate = record.hasChildren;
        if (!isDate) {
          params.hour = record.timeStr;
          params.staticsDate = record.childDate;
          diaTitle = `${record.platformName} ${record.childDate} 日 ${record.timeStr} 时 `;
        }

        if (type == 'uvTimes') {
          if (isDate) {
            await getUvTimesTableData(params).then(({data}) => {
              return this.diaTabData = data.result;
            });
          } else {
            await getUvTimesTableDataOfHours(params).then(({data}) => {
              return this.diaTabData = data.result;
            })
          }
          this.diaTitleText = `${diaTitle} UV次数`;
        } else if (type == "uvDays") {
          if (isDate) {
            await getUvDaysTableData(params).then(({data}) => {
              return this.diaTabData = data.result;
            });
          } else {
            await getUvDaysTableDataOfHour(params).then(({data}) => {
              return this.diaTabData = data.result;
            });
          }
          this.diaTitleText = `${diaTitle} UV天数`;
        }
        this.fullscreenLoading = false;

      }
    }
  }
</script>
<style lang="less" scoped>
  .containerBox {
    /*margin-top: 20px;*/
  }
</style>
